package splitencrypt

// 主要编写读取文件  将文件读取成流  并且分割流为指定大小
import (
	"fmt"
	"os"
)

// 已20M为一个文件分割
const SPLIT_SIZE int32 = 1024 * 1024 * 20

var gFileName string

// 从绝对路径来读取文件成为文件流
func readFileToStream(fileName string) ([]byte, error) {
	f, err := os.Open(fileName)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	var payload []byte
	isContinue := true
	for isContinue {
		buf := make([]byte, 1024)
		switch nr, err := f.Read(buf[:]); true {
		case nr < 0:
			fmt.Fprintf(os.Stderr, "cat: error reading: %s\n", err.Error())
			os.Exit(1)
		case nr == 0: // EOF
			isContinue = false
		case nr > 0:
			payload = append(payload, buf...)
		}
	}
	fmt.Printf("read File To Stream!")
	return payload, nil
}

// 分割流为指定大小
func split(fileStream []byte, size int) ([][]byte, error) {
	var fileLength = len(fileStream)
	var ySize = fileLength / size
	var resultByte [][]byte
	for i := 0; i < ySize; i++ {
		xFileByte := make([]byte, 0, size)
		if ((ySize + 1) * i) <= fileLength {
			tempByteSlice := fileStream[ySize*i : (ySize*i + size - 1)]

		} else {
			for j := 0; j < size; j++ {
				if (ySize*i + j + 1) <= fileLength {
					tempByteSlice := fileStream[ySize*i+j : ySize*i+j+1]
					tempByte := tempByteSlice[0]
					xFileByte = append(xFileByte, tempByte)
				} else {
					xFileByte = append(xFileByte, 0)
				}
			}
		}

		resultByte = append(resultByte, xFileByte)
	}

	fmt.Printf("split stream to serveral parts!")
	return resultByte, nil
}

// 将文件按拆分的流保存
func saveFiles(fileStream [][]byte) ([]byte, error) {
	var r []byte
	fmt.Printf("save Files!")
	return r, nil
}
